﻿import {useRef, useEffect} from "react";
import {useFrame} from "@react-three/fiber";
import {useGLTF} from "@react-three/drei";
import * as THREE from "three";

function WeatherModel({modelPath}) {
    const {scene} = useGLTF(modelPath); // 加载模型
    const meshRef = useRef();
    
    // 控制旋转
    useFrame(() => {
        if (meshRef.current) {
            meshRef.current.rotation.x = Math.sin(Date.now() * 0.001) * 0.3; // 不超过 45 度
            meshRef.current.rotation.y = Math.cos(Date.now() * 0.001) * 0.3; // 不超过 45 度
        }
    });
    
    // 监听模型加载并调整缩放
    useEffect(() => {
        if (meshRef.current) {
            // 获取模型的包围盒尺寸
            const box = new THREE.Box3().setFromObject(scene);
            const modelSize = new THREE.Vector3();
            box.getSize(modelSize); // 获取模型的宽度、高度和深度
            
            // 应用缩放
            meshRef.current.scale.set(1.2, 1.2, 1.2);
            
            // 确保材质的颜色和纹理正确
            meshRef.current.traverse((child) => {
                if (child.isMesh) {
                    // 确保材质的颜色和纹理正确
                    if (child.material) {
                        child.material.needsUpdate = true; // 确保材质更新
                        if (child.material.map) {
                            child.material.map.encoding = THREE.sRGBEncoding; // 确保纹理使用正确的颜色空间
                        }
                    }
                }
            });
        }
    }, [scene]);
    
    return (
        <group>
            {/* 环境光和点光源 */}
            <ambientLight intensity={0.8}/>
            <pointLight position={[0, 5, 10]} intensity={1.0}/>
            <pointLight position={[0, 5, -10]} intensity={1}/>
            <directionalLight position={[0, 10, 5]} intensity={1}/>
            
            {/* 加载模型 */}
            <primitive object={scene} ref={meshRef}/>
        </group>
    );
}

export default WeatherModel;